#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

console.log('🔍 验证 SuotaScanner.ets 修复情况...\n');

const scannerPath = 'src/main/ets/components/plugin/SuotaLib/scan/SuotaScanner.ets';

if (!fs.existsSync(scannerPath)) {
    console.log('❌ SuotaScanner.ets 文件不存在');
    process.exit(1);
}

const content = fs.readFileSync(scannerPath, 'utf8');

// 检查关键功能
const checks = [
    {
        name: 'pendingScan 属性定义',
        pattern: /private\s+pendingScan:\s*boolean\s*=\s*false/,
        required: true
    },
    {
        name: 'isScanning getter方法',
        pattern: /get\s+isScanning\(\):\s*boolean/,
        required: true
    },
    {
        name: 'onBluetoothUpdatedState 方法存在',
        pattern: /onBluetoothUpdatedState\s*\(/,
        required: true
    },
    {
        name: 'PoweredOn 分支处理',
        pattern: /case\s+BluetoothState\.PoweredOn:/,
        required: true
    },
    {
        name: 'PoweredOff 分支处理',
        pattern: /case\s+BluetoothState\.PoweredOff:/,
        required: true
    },
    {
        name: 'pendingScan 检查逻辑',
        pattern: /if\s*\(\s*this\.pendingScan\s*\)/,
        required: true
    },
    {
        name: '重启扫描调用 - scanDevices()',
        pattern: /this\.scanDevices\(\)/,
        required: true
    },
    {
        name: 'isScanning 检查逻辑',
        pattern: /if\s*\(\s*this\.isScanning\s*\)/,
        required: true
    },
    {
        name: '停止扫描调用 - stopScan()',
        pattern: /this\.stopScan\(\)/,
        required: true
    }
];

let allPassed = true;

checks.forEach(check => {
    const found = check.pattern.test(content);
    const status = found ? '✅' : '❌';
    console.log(`${status} ${check.name}: ${found ? '通过' : '失败'}`);
    
    if (check.required && !found) {
        allPassed = false;
    }
});

console.log('\n📊 详细分析:');

// 检查 onBluetoothUpdatedState 方法的完整实现
const methodMatch = content.match(/onBluetoothUpdatedState\s*\([^)]*\)\s*:\s*void\s*\{([\s\S]*?)\n\s*\}/);
if (methodMatch) {
    const methodBody = methodMatch[1];
    console.log('✅ onBluetoothUpdatedState 方法实现完整');
    
    // 检查是否包含 scanDevices 调用
    if (methodBody.includes('this.scanDevices()')) {
        console.log('✅ 包含 scanDevices() 调用 - 修复成功！');
    } else {
        console.log('❌ 缺少 scanDevices() 调用');
        allPassed = false;
    }
    
    // 检查是否包含 stopScan 调用
    if (methodBody.includes('this.stopScan()')) {
        console.log('✅ 包含 stopScan() 调用');
    } else {
        console.log('❌ 缺少 stopScan() 调用');
        allPassed = false;
    }
} else {
    console.log('❌ onBluetoothUpdatedState 方法实现不完整');
    allPassed = false;
}

console.log('\n' + '='.repeat(50));
if (allPassed) {
    console.log('🎉 所有检查通过！SuotaScanner 已与 iOS 版本对齐');
    console.log('✅ pendingScan 状态管理已实现');
    console.log('✅ 蓝牙状态变化时的自动重启扫描已实现');
    console.log('✅ 蓝牙关闭时的自动停止扫描已实现');
    process.exit(0);
} else {
    console.log('❌ 发现问题，请检查上述失败项');
    process.exit(1);
}